
package cn.com.pusai.core.config;

import cn.com.pusai.core.util.StringUtil;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PropertyExpander
{

	public static final Pattern EXPANSION_PATTERN = Pattern.compile("[$][{]([^}]*)[}]");

	public PropertyExpander()
	{
	}

	public static String expandProperties(String input, Map props)
	{
		if (StringUtil.isBlank(input))
			return input;
		Matcher matcher = EXPANSION_PATTERN.matcher(input);
		StringBuffer expanded = new StringBuffer(input.length());
		String value;
		for (; matcher.find(); expanded.append(value))
		{
			String propName = matcher.group(1).trim();
			value = (String)props.get(propName);
			if (value == null)
				value = matcher.group();
			matcher.appendReplacement(expanded, "");
		}

		matcher.appendTail(expanded);
		return expanded.toString();
	}

	public static String expandSystemProperties(String input)
	{
		Map map = System.getProperties();
		return expandProperties(input, map);
	}

}
